<template>
  <div class="policy_holder">
    <div class="name">
      <span></span>{{Data.attrName}}
    </div>
    <div class="scan">
      身份信息识别
      <img src="@/assets/img/scan.png" alt="">
      <van-uploader class="opacity" :after-read="onRead"  />
    </div>
  </div>
</template>
<script>
import publicfunc from "@/assets/js/publicFunc.js";
export default {
  name: "id_card",
  props: {
    config: {
      type: Object,
      required: true
    },
    parentIndex: Number,
    itemIndex: Number
  },
  // props: ['detail'],
  data() {
    return {
      Data: {},
      files: {}
    };
  },
  mounted() {
    this.Data = this.config;
  },
  methods: {
    // 组件方法 获取 流
    onRead(file) {
      this.files.name = file.file.name; // 获取文件名
      this.files.type = file.file.type; // 获取类型
      this.picValue = file.file; // 文件流
      this.imgPreview(this.picValue);
    },
    // 处理图片
    imgPreview(file) {
      let self = this;
      let Orientation;
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return;
      if (/^image/.test(file.type)) {
        // 创建一个reader
        let reader = new FileReader();
        // 将图片2将转成 base64 格式
        reader.readAsDataURL(file);
        // 读取成功后的回调
        reader.onloadend = function() {
          // console.log(this.result);
          let result = this.result;
          let img = new Image();
          img.src = result;
          //判断图片是否大于500K,是就直接上传，反之压缩图片
          if (this.result.length <= 500 * 1024) {
            self.headerImage = this.result;
            self.postImg();
          } else {
            img.onload = function() {
              let data = self.compress(img, Orientation);
              self.headerImage = data;
              self.postImg();
            };
          }
        };
      }
    },
    // 压缩图片
    compress(img, Orientation) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      //瓦片canvas
      let tCanvas = document.createElement("canvas");
      let tctx = tCanvas.getContext("2d");
      // let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      let ratio;
      if ((ratio = width * height / 4000000) > 1) {
        // console.log("大于400万像素");
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      //    铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      //如果图片像素大于100万则使用瓦片绘制
      let count;
      if ((count = width * height / 1000000) > 1) {
        // console.log("超过100W像素");
        count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
        //      计算每块瓦片的宽和高
        let nw = ~~(width / count);
        let nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            );
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }

      //进行最小压缩
      let ndata = canvas.toDataURL("image/jpeg", 0.1);
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    },
    //将base64转换为文件
    dataURLtoFile(dataurl) {
      var arr = dataurl.split(","),
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], this.files.name, {
        type: this.files.type
      });
    },
    postImg() {
      this.$toast.loading({
        message: "识别中...",
        duration: 0
      });
      let file = this.dataURLtoFile(this.headerImage);
      let formData = new FormData();
      formData.append("ImageFile", file);
      this.$api.dataPublicPost(
        "/api/v1/idcardocr/GetInfo?UserAppKey="+this.$api.getData().ocrAppKey,
        formData,
        result => {
          this.$toast.clear();
          if (result.resultCode == 200) {
            this.$emit(
              "getIDCard",
              this.config.attrName,
              this.parentIndex,
              result.data
            );
          } else {
            this.$toast(result.resultMsg);
          }
          // console.log(result)
        }
      );
    }
  }
};
</script>
<style lang="less">
.policy_holder {
  height: 1.093333rem;
  background: #fafafa;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 0 0.533333rem;
  box-shadow: inset 0px 5px 15px -15px #A1A1A1, inset 0px -5px 15px -15px #A1A1A1;
  .name,
  .scan {
    height: 100%;
    width: 50%;
    display: flex;
    flex-direction: row;
    align-items: center;
    font-size: 0.4rem;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    color: rgba(110, 154, 251, 1);
    span {
      width: 0.08rem;
      height: 0.32rem;
      background: rgba(43, 103, 254, 1);
      border-radius: 0.053333rem;
      margin-right: 0.213333rem;
    }
  }
  .scan {
    justify-content: flex-end;
    font-size: 0.32rem;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(160, 160, 160, 1);
    line-height: 0.453333rem;
    position: relative;
    .opacity {
      opacity: 0;
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      .van-uploader__upload {
        width: 3rem;
        height: 1.066667rem;
        margin: 0;
      }
    }
    img {
      width: 0.32rem;
      height: 0.32rem;
      margin-left: 0.16rem;
    }
  }
}
</style>

